Advent of Code - Day 4: Camp Cleanup

Fourth day of the advent of code using R

advent of code
Published

December 4, 2022

Part 1

Input

input <- readLines("input.txt")

head(input, 10)
 [1] "7-24,8-8"    "2-75,37-51"  "47-78,20-39" "53-91,34-53" "13-50,14-50"
 [6] "93-93,20-93" "74-80,48-81" "30-87,27-38" "6-93,7-94"   "56-98,12-49"

Code

# Function to count the number of overlapping pairs
count_overlapping_pairs <- function(pairs) {
  # Initialize a counter variable
  count <- 0

  # Loop through each pair
  for (pair in pairs) {
    # Split the pair into its start and end parts
    parts <- unlist(strsplit(pair, ","))
    
    first_elf <- as.numeric(unlist(strsplit(parts[1], "-")))
    second_elf <-  as.numeric(unlist(strsplit(parts[2], "-")))
    
    first_set <- c(first_elf[1]:first_elf[2])
    second_set <- c(second_elf[1]:second_elf[2])
    
    
    if (identical(first_set[first_set %in% second_set],first_set) || identical(second_set[second_set %in% first_set],second_set)) {
      count <- count + 1
    }
  }

  # Return the count
  return(count)
}
result <- count_overlapping_pairs(input)

Result

There are a total of 562 fully overlapping pairs.

Part 2

# Function to count the number of overlapping pairs
count_overlapping_pairs <- function(pairs) {
  # Initialize a counter variable
  count <- 0

  # Loop through each pair
  for (pair in pairs) {
    # Split the pair into its start and end parts
    parts <- unlist(strsplit(pair, ","))
    
    first_elf <- as.numeric(unlist(strsplit(parts[1], "-")))
    second_elf <-  as.numeric(unlist(strsplit(parts[2], "-")))
    
    first_set <- c(first_elf[1]:first_elf[2])
    second_set <- c(second_elf[1]:second_elf[2])
    
    
    if (length(intersect(first_set, second_set) > 0)) {
      count <- count + 1
    }
  }

  # Return the count
  return(count)
}

result <- count_overlapping_pairs(input)

There are a total of 924 partialy overlapping pairs.